using IQIGame.Onigao.Game;

namespace IQIGame.Onigao.Logic
{
    /// <summary>
    /// 怪物追击行为组件
    /// </summary>
    public class LgChaseEnemyComponent : LogicBaseEntityComponent
    {
        private LevelEntity _entity;
        private int _refreshChasingPointTimer;

        public override uint MaxStore => 50;

        public Vector3Logic chaseStartPos { get; internal set; }
        public Vector3Logic chaseStartDir { get; internal set; }
        public LevelHeroEntity lockingEntity { get; private set; }

        public override void Awake(BaseEntity entity)
        {
            _entity = entity as LevelEntity;
            chaseStartPos = _entity.position;
            chaseStartDir = _entity.dir;
            _refreshChasingPointTimer = LgLevelConst.PursuitSetTargetInterval;
        }

        public void LockEntity(LevelHeroEntity entity)
        {
            lockingEntity = entity;
        }

        public override void LogicOnUpdate()
        {
            //追击逻辑
            if (lockingEntity != null)
            {
                _refreshChasingPointTimer++;
                //必须间隔，否则实体将不断重启寻路（英雄可能会不断变换位置），从而卡死。
                //目前没有必要因为这个逻辑修改寻路底层去支持每帧刷新的寻路行为，因为只有少量不断调整目标点的行为（比如追击）会有此问题。
                //如果不做间隔，性能也会很差，因为每帧都会请求寻路底层重新计算寻路数据
                if (_refreshChasingPointTimer >= LgLevelConst.PursuitSetTargetInterval)
                {
                    _refreshChasingPointTimer = 0;
                    _entity.StartNavigation(lockingEntity.position, (int)(_entity.moveSpeed * LgLevelConst.MonsterChaseSpeedRatio));
                }
            }
        }

        public void SetActive(bool value)
        {
            _entity?.navigator.SetActive(value);
        }

        public override void OnRelease()
        {
            if (_entity.navigator.isNavigating)
            {
                _entity.StopNavigation();
            }
            lockingEntity = null;
            chaseStartPos = default;
            chaseStartDir = default;
            _entity = null;
            _refreshChasingPointTimer = 0;
        }
    }
}
